2017-04-12 15 views
5

मेरे पास एक विशिष्ट मामला है जहां मुझे जारी रखने से पहले एसिंक कॉल परिणाम का इंतजार करना होगा। मैं async/प्रतीक्षा कीवर्ड का उपयोग कर रहा हूं, लेकिन कोई भाग्य नहीं है। किसी भी मदद की सराहना की।जावास्क्रिप्ट async/काम नहीं कर रहा

यह काम करने की कोशिश करने का मेरा प्रयास है, संख्या संख्यात्मक क्रम में होनी चाहिए।

function sleep(ms) { 
 
    return new Promise(resolve => setTimeout(resolve, ms)); 
 
} 
 

 
async function demo() { 
 
    document.writeln('2...'); 
 
    await sleep(2000); 
 
    document.writeln('3...'); 
 
} 
 

 
document.writeln('1...'); 
 
demo(); 
 
document.writeln('4.');

+3

करने के लिए कॉल प्रतीक्षा करनी क्यों वास्तव में आप सोचते हैं कि वे संख्यात्मक क्रम में होना चाहिए? '3' आखिरी बार आता है, क्योंकि यह आखिरी चीज है जो वादा समारोह के बाद निष्पादित हो जाती है। क्या आप उम्मीद करते हैं कि '1 ... 2 ... 3 ... 4.' बहुत अंत में प्रदर्शित किया जाएगा? फिर 'document.writeln' का उपयोग न करें। इसके बजाए मानक डोम एपीआई का प्रयोग करें। – Xufox

उत्तर

1

आप async function के बाद .then() उपयोग करना चाहिए।

function sleep(ms) { 
 
    return new Promise(resolve => setTimeout(resolve, ms)); 
 
} 
 

 
async function demo() { 
 
    document.writeln('2...'); 
 
    await sleep(2000); 
 
    document.writeln('3...'); 
 
} 
 

 
document.writeln('1...'); 
 
demo().then(() => { 
 
    document.writeln('4.'); 
 
});

3

async समारोह एक Promise वापस आ जाएगी, ताकि आप demo

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)) 

const demo = async() => { 
    console.log('2...') 
    await sleep(2000) 
    console.log('3...') 
} 

const blah = async() => { 
    console.log('1...') 
    await demo() 
    console.log('4.') 
} 

blah() 
संबंधित मुद्दे