【发布时间】:2018-04-02 04:58:03
【问题描述】:
我正在尝试同步运行 2 个函数。第一个函数的执行速度比第二个函数慢很多。我需要它从第 1 次到第 2 次同步运行。
//1st function
function first(){
$.getJSON("/update/", () => {
//updates
})
}
//2nd function
function second(){
//triggers some event
}
此时,我已经尝试使用 Promise,但无济于事,失败了
//Promise
var promiseVar = new Promise((resolve, reject) =>{
first(); //run the first function
//note: first() will take more time to run because it's
//grabbing something from the server to update to client
resolve('Success');
})
promiseVar.then((msg)=>{
console.log(msg);
second();
})
通过使用 Promise,它在加载第一个函数时仍然执行第二个函数。我怎样才能让这个按顺序运行?
【问题讨论】:
-
这个一般性问题在堆栈溢出时已被问了数百次。
-
@jfriend00 你估计这个问题比为什么
.then()未定义链接到不返回Promise的函数调用,或者为什么链接.then()的值未定义之前的.then()没有返回任何值,或者前两个查询的查询次数与当前查询的次数相同? -
@guest271314 - 我不算数。关键是 OP 可以做一些研究并找到很多相关的答案。
标签: javascript jquery asynchronous promise synchronous