gpt4 book ai didi

javascript - 将回调转换为 Promise 语法

转载 作者:太空宇宙 更新时间:2023-11-04 03:15:15 26 4
gpt4 key购买 nike

为了更好地理解 Promise 语法,我尝试将以下伪代码转换为现代 JavaScript。

这是旧代码,其中包含臭名昭著的回调 hell :

1995 JavaScript

var floppy = require( 'floppy' );

floppy.load( 'disk1', function( data1 ) {
floppy.prompt( ' Please insert disk 2', function() {
floppy.load( 'disk2', function( data2 ) {
floppy.prompt( ' Please insert disk 3', function() {
floppy.load( 'disk3', function( data3 ) {
floppy.prompt( 'Please insert disk 4', function() {
// If Node.js would've existed in 1995.
} );
} );
} );
} );
} );
} );

请帮我将上面的内容转换为带有 Promise 语法的 JavaScript(无 async/await)。我是 Promise 新手,但这就是我的想法。语法、嵌套和功能与上面的代码相同吗?如果没有,请帮助我将回调疯狂转换为带有 Promises 的漂亮 JavaScript。

更新代码

const floppy = require( 'floppy' );

floppy.load( 'disk1' )
.then( data1 => {
floppy.prompt( 'Please insert disk 2' );
} )
.then(
floppy.load( 'disk2' )
)
.then( data2 => {
floppy.prompt( 'Please insert disk 3' );
} )
.then(
floppy.load( 'disk3' )
)
.then( data3 => {
floppy.prompt( 'Please insert disk 4' );
} )
.then(
// Node.js using Promises avoids callback hell!
);

最佳答案

首先使用以下方法对您的floppy 对象进行猴子补丁:

floppy.loadAsync = function(d) {
return new Promise(resolve => {
floppy.load(d, resolve);
});
};
floppy.PromptAsync = function(message) {
return new Promise(resolve => {
floppy.load(message, resolve);
});
};

现在你可以写:

floppy.loadAsync('disk1')
.then(data1 => floppy.promptAsync(' Please insert disk 2'))
.then(() => floppy.loadAsync('disk2'))
.then(data2 => floppy.promptAsync(' Please insert disk 3'))
.then(() => floppy.loadAsync('disk3'))
.then(data3 => floppy.promptAsync(' Please insert disk 4'));

如果您想在最终回调中访问 data1data2data3data4(看起来很可能),那么您将拥有 range of options available to you .

例如,使用“打破链条”方法,您可以这样写:

var promise1a = floppy.loadAsync('disk1');
var promise1b = promise1a.then((data1) => floppy.promptAsync(' Please insert disk 2'));

var promise2a = promise1b.then(() => floppy.loadAsync('disk2'));
var promise2b = promise2a.then((data2) => floppy.promptAsync(' Please insert disk 3'));

var promise3a = promise2b.then(() => floppy.loadAsync('disk3'));
var promise3b = promise3a.then((data3) => floppy.promptAsync(' Please insert disk 4'));

var promise4a = promise3b.then(() => floppy.loadAsync('disk4'));

Promise.all([promise1a, promise2a, promise3a, promise4a]).then((data) => {
var data1 = data[0];
var data2 = data[1];
var data3 = data[2];
var data4 = data[3];
});

关于javascript - 将回调转换为 Promise 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com