gpt4 book ai didi

javascript - 修复尝试将回调示例重写为 Promise 时出现的错误

转载 作者:行者123 更新时间:2023-12-01 01:21:23 24 4
gpt4 key购买 nike

我试图使用非常简单的示例来理解回调和 promise 。我想出了如何将为什么需要回调的示例重写为工作“回调表单”。然而,我坚持将其重写为 promise

我试图按照此处的示例使这项工作成为一个 promise :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Basic_Example

但是我在使其正常工作时遇到了一些麻烦。

首先,我得到了这段代码,显示了为什么回调很重要:

function first(){
// Simulate a code delay
setTimeout( function(){
console.log(1);
}, 500 );
}

function second(){
console.log(2);
}

first();
second();

然后我使用回调重写了这个:


function first(callback){
// Simulate a code delay
setTimeout( function(){
console.log(1);
callback();
}, 500 );

}

function second(){
console.log(2);
}

first(second);
// second();


现在我想知道如何将其重写为 promise 。


let first = new Promise( function (resolve, reject){
// Simulate a code delay
setTimeout( function(){
console.log(1);
resolve('success')
}, 500 );
});

function second(){
console.log(2);
}

first.then(second());


我希望它先输出1,然后输出2,现在它输出2,然后1。

最佳答案

这是应该执行您所要求的代码。您的代码中的问题是您实际上立即调用了 Second() :

first.then(second());

而不是将函数作为参数传递(then() 将在第一个 Promise 解决时调用它):

let first = new Promise( function (resolve, reject){
// Simulate a code delay
setTimeout( function(){
console.log(1);
resolve('success')
}, 500 );
});

function second(){
console.log(2);
}

first.then(second);

关于javascript - 修复尝试将回调示例重写为 Promise 时出现的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54201994/

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