这个承诺的位置我做错了什么?
我需要先完成第一个功能的所有元素,然后才能触发第二个功能。
谢谢。
功能1:
var promise1 = $("#button-1").on('click', async new Promise(function(resolve, reject) {
csInterface.evalScript("Duplicate()");
await SafeMode();
csInterface.evalScript("FlattenImage()");
await SafeMode();
csInterface.evalScript("ConverttosRGB()");
await SafeMode();
csInterface.evalScript("Resolution300PPI()");
await SafeMode();
csInterface.evalScript("SetBackgroundtoLayer()");
await SafeMode();
csInterface.evalScript("Postcard1()");
resolve();
}));
功能2:
promise1.then(function() {
// next function here
});
答案 0 :(得分:3)
promise1不是一个承诺,实际上是一个jQuery对象。制作一个可以生成您所需的诺言的函数(见下文)。
const promise1 =() => new Promise(async function(resolve, reject) {
/** Commented so you can see that it works
csInterface.evalScript("Duplicate()");
await SafeMode();
csInterface.evalScript("FlattenImage()");
await SafeMode();
csInterface.evalScript("ConverttosRGB()");
await SafeMode();
csInterface.evalScript("Resolution300PPI()");
await SafeMode();
csInterface.evalScript("SetBackgroundtoLayer()");
await SafeMode();
csInterface.evalScript("Postcard1()");*/
//Adding time
setTimeout(()=>{
console.log("promise1");
resolve();
}, 500);
})
$("#button-1").on('click', () => {
promise1().then(() => {
//next bit of your code here
console.log("next");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button-1">Click me</button>
答案 1 :(得分:1)
on()
函数不会返回promise,您需要先声明异步函数,然后将其作为回调回调并与THEN链接起来。
此外,异步功能将自动返回Promise,而无需您自己构建。
const resolveAfter1Seconds = function(id) {
return new Promise(resolve => {
setTimeout(function() {
resolve("resolution " + id);
}, 1000);
});
};
const callback = async function() {
console.log("in callback", "start");
let res = await resolveAfter1Seconds(1);
console.log("in callback 1", res);
res = await resolveAfter1Seconds(2);
console.log("in callback 2", res);
res = await resolveAfter1Seconds(3);
console.log("in callback 3", res);
return "what you want your promise to finally return";
};
$("#button-1").on('click', () => {
callback().then(x => console.log("THEN", x))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button-1">Click me!</button>