Move object/variable away from async function

后端 未结 2 1849
故里飘歌
故里飘歌 2021-01-28 18:34

I understand that this is a basic question, but I can\'t figure it out myself, how to export my variable \"X\" (which is actually a JSON object) out of \"for\" cycle. I have tri

2条回答
  •  被撕碎了的回忆
    2021-01-28 19:06

    Javascript builds on the concept of promises. When you ask getData to to do its work, what is says is that, "OK, this is going to take some time, but I promise that I'll let you know after the work is done. So please have faith on my promise, I'll let you know once the work is complete", and it immediately gives you a promise to you.

    That's what you see as promise.pending. It's pending because it is not completed yet. Now you should register a certain task (or function) with that promise for getData to call when he completes the work.

    function doSomething(){
    var promiseArray = [];
    for (let i = 0; i < server.length; i++) {
        const fetch = require("node-fetch");
        const url = ''+(server[i].name)+'';
        const getData = async url => {
            try {
                const response = await fetch(url);
                return await response.json();
            } catch (error) {
            console.log(error);
            }
        };
        promiseArray.push(getData(url)); // keeping track of all promises
     }
    
     return Promise.all(promiseArray); //see, I'm not registering anything to promise, I'm passing it to the consumer
    
    }
    
    function successCallback(result) {
      console.log("It succeeded with " + result);
    }
    
    function failureCallback(error) {
      console.log("It failed with " + error);
    }
    
    let promise = doSomething(); // do something is the function that does all the logic in that for loop and getData
    promise.then(successCallback, failureCallback);
    

提交回复
热议问题