如果你想在 JavaScript 中调用回调之后执行代码,那么你可以把它放在回调之后:
function demoCallback(callback) {
callback()
console.log("I execute second")
}
demoCallback(() => {
console.log("I execute first")
})
是否可以在函数范围内使用 ES6 Promise 做同样的事情?假设我有一个返回 Promise 的函数:
function demoPromise() {
return new Promise((resolve, reject) => {
resolve()
console.log("I execute first")
})
}
demoPromise().then(() => { console.log("I execute second") })
在 之后插入的代码解决 一旦 Promise 被解决,但在 之前执行然后在函数范围之外调用。 有没有一种方法可以在两者之后执行代码,但在函数范围内执行?
最佳答案
Is it possible to do the same thing with an ES6 Promise from within the scope of the function?
不,这是不可能的。
then
回调总是异步运行,这包括与 resolve()
相关的异步。称呼。(也就是说,promise 回调是排队的,所以你可以滥用这个队列来让你的代码落后于另一个:
function demoPromise() {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
p.then(() => {
console.log("I execute second");
}); // because I will be scheduled second
}, 1000);
});
return p;
}
demoPromise().then(() => {
console.log("I execute first");
}); // because I was scheduled first
但请不要这样做)
If you want to execute code after a callback is called in JavaScript
那么你可能不应该只返回一个 promise 。在执行您的代码之前,执行您想要的回调:
function demoPromise(callback) {
return new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
}).then(() => {
return callback();
}).then(res => {
console.log("I execute second");
});
}
demoPromise(() => {
console.log("I execute first");
}).then(() => {
console.log("I execute last");
});
这被称为 disposer pattern并且对于处理资源非常有用。
关于javascript - ES6 Javascript Promise - 在调用 .then() 之后执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480968/