如何链接两个。然后在javascript中?

如何链接两个。然后在javascript中?,javascript,async-await,fetch,Javascript,Async Await,Fetch,我在使用.then时遇到了一些问题。我有一个fetch函数,然后使用结果更新一个price数组。我想让update函数等待fetch函数结束。我不会成功的。有什么想法吗? 多谢各位 function FetchPrices() { return new Promise(function(resolve, reject) { console.log("j'entre dans FetchPrices") var call = 'https://min-api

我在使用.then时遇到了一些问题。我有一个fetch函数,然后使用结果更新一个price数组。我想让update函数等待fetch函数结束。我不会成功的。有什么想法吗? 多谢各位

function FetchPrices() {
    return new Promise(function(resolve, reject) {
        console.log("j'entre dans FetchPrices")
        var call = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms='+ GetCoinsListToFetch() + '&tsyms=BTC,USD,EUR&api_key=55baa6d4b58517d610476c';
        fetch(call)
        .then(function (response) {
            response.json()
            .then(function (value) {
                console.log("je suis dans le .then du fetch")
                var v = value
                pricesList = v;
                console.log(v);
                console.log("fin du fetch")

            });
        });
    })
}

在完成第一个函数后,第二个函数UpdatePrices似乎不适用于第二个函数

第二个函数没有被调用,因为第一个函数返回的承诺没有被解析,因为解析从未被调用。您可以通过调用resolve手动解析,但最好只返回由fetch函数创建的承诺:

function FetchPrices() {
  console.log("j'entre dans FetchPrices")
  var call = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms='+ GetCoinsListToFetch() + '&tsyms=BTC,USD,EUR&api_key=440f35b466d7a82c3f7f94fd64f6436155c272410055baa6d4b58517d610476c';
  return fetch(call)
    .then(function (response) {
      response.json()
        .then(function (value) {
          console.log("je suis dans le .then du fetch")
          var v = value
          pricesList = v;
          console.log(v);
          console.log("fin du fetch")

        });
    });
}

正如@antonku所提到的,您应该直接使用fetch返回的承诺

根据经验,只有当你想要回报的东西还不是承诺时,你才应该使用新的承诺

function FetchPrices() {
  var call = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms='+ GetCoinsListToFetch() + '&tsyms=BTC,USD,EUR&api_key=55baa6d4b58517d610476c';
  return fetch(call).then(response => response.json())
}
为什么要混合异步和异步呢?我认为你这样做会更干净

const fetchFn = async () => {
   const {json} = await fetch('your url');
   const data = await json();
   return data;
}

在test2Fn中,您可以这样做

const test2Fn = async () => {
    const pricesList = await fetchFn();
    UpdatePrices();
}

希望这也有帮助

见鬼了!我在console.logfin du fetch之后的行上添加了解析,它似乎正在工作!非常感谢你
const fetchFn = async () => {
   const {json} = await fetch('your url');
   const data = await json();
   return data;
}

const test2Fn = async () => {
    const pricesList = await fetchFn();
    UpdatePrices();
}