简体   繁体   中英

How can I await promise().done() with typescript?

I know how to create a standard promise and use async/await to it but how can I await jquery promise().done() with typescript?

Current:

$('#sun').hide('slide', {direction:'right'}, 200).promise().done(function () {
    $('#rain').show('slide', {direction:'left'}, 200).promise().done(function () {
        console.log('ok!');
    });
});

I would like to do in this way but it does not work:

await $('#sun').hide('slide', {direction:'right'}, 200).promise().done(); 
await $('#rain').show('slide', {direction:'left'}, 200).promise().done();
console.log('ok!');

Try removing the done() call from the ends of your promise() calls. Without specifically looking into the jQuery promise implementation I would imagine calling done() without an argument returns undefined or an otherwise unawaitable result, so you're trying to await undefined .

Try awaiting the promise() call instead:

await $('#sun').hide('slide', {direction:'right'}, 200).promise(); 
await $('#rain').show('slide', {direction:'left'}, 200).promise();
console.log('ok!');

A jquery promise works in the same manner as a vanilla promise

An example on how it works, convert this:

 var div = $( "<div>" ); div.promise().done(function( arg1 ) { // Will fire right away and alert "true" console.log( this === div && arg1 === div ); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

to this:

 var div = $( "<div>" ); async function run(){ const arg1 = await div.promise(); console.log(arg1 === div ); } window.onload = run; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

Solution:

await $('#sun').hide('slide', {direction:'right'}, 200).promise(); 
await $('#rain').show('slide', {direction:'left'}, 200).promise();
console.log('ok!');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM