Ste*_*ter 3 javascript promise es6-promise
我创建了两个Promise,但是我没有对这些Promise运行then方法。然而,一旦promise对象超出范围,promise代码就会像.then
被调用一样运行。
Promise
在不调用.then
方法的情况下如何解决?
我问是因为我想用Promise
对象加载数组,然后按顺序运行promise。
function promises_createThenRun() {
const p1 = createPromise1();
const p2 = createPromise2();
console.log('before hello');
alert('hello');
console.log('after hello');
// the two promises run at this point. What makes them run?
}
function createPromise1() {
let p1 = new Promise((resolve, reject) => {
window.setTimeout(() => {
console.log('timer 1');
resolve();
}, 2000);
});
return p1;
}
function createPromise2() {
let p2 = new Promise((resolve, reject) => {
window.setTimeout(() => {
console.log('timer 2');
resolve();
}, 1000);
});
return p2;
}
Run Code Online (Sandbox Code Playgroud)
Promise构造函数中的代码在创建promise时运行,并且同步运行,这使某些人感到惊讶。因此即使没有then()
一切,它仍然可以运行。
new Promise(resolve => console.log("running"))
Run Code Online (Sandbox Code Playgroud)
setTimeout
但是,回调中的代码直到被调用后才会运行,但即使没有then()
new Promise(resolve => {
console.log("promise created")
setTimeout(() => console.log("this runs later"), 1000)
})
Run Code Online (Sandbox Code Playgroud)
打电话时,.then
您只需设置一个“回调”,说明承诺完成后会发生什么。因此,无论是否声明此类回调,都会调用承诺。
想象一下调用 AJAX 请求的承诺。调用.then
并将函数传递给它将使它在 ajax 调用完成时运行(成功或失败,如超时或其他错误)。但是不调用.then
不会停止要运行的请求。您根本不会对请求的结果做出反应。