Fetch 同步异步问题

#1
let info = [];

fetch('url', {
      method: 'POST',
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: JSON.stringify({
        "m": "activity",
        "c": "youxi",
      })
    }).then(res => res.json()).then(json => {
      if (json.status === 0) {
        Toast.success("获取成功");
        info = json.data.map((v, i) => {
          return {label: v.name, ratio: v.rate}
        });
       console.log(info) // 这里可以正常输出
      } else if (json.status === 1) {
        Toast.fail("获取失败")
      }
    })
    .catch(error => {
      throw error
    });

   console.log(info) // 这里不可以正常输出 想让他在这也正常输出
#2

then 作用域是单独的 怎么赋值呢?

#3
let info = [];

function getData() {
    return new Promise((resolve, reject) => {
        fetch('url', {
            method: 'POST',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: JSON.stringify({
                "m": "activity",
                "c": "youxi",
            })
        }).then(res => res.json()).then(json => {
            if (json.status === 0) {
                console.log("获取成功");
                info = json.data.map((v, i) => {
                  return {label: v.name, ratio: v.rate}
                });
                console.log(info) // 这里可以正常输出
                resolve(info)
            } else if (json.status === 1) {
                Toast.fail("获取失败")
                reject('失败了')
            }
        })
            .catch(error => {
                throw error
            });
    })
}

async function foo() {
    info = await getData()
    console.log(info) // 这里不可以正常输出 想让他在这也正常输出
}

foo()
1 Like
Fetch 回调函数里赋值失效 bug吗?
#4

你需要理解的是 同步和异步的问题。 就类似

var info;
setTimeout(function() {
info = “Set a value after 1000 ms”;
console.log(info);
}, 1000);
console.log(info);