需要指导!尝试了解fetch()和Promises [英] Need guidance! Trying to learn about fetch() and Promises

查看:55
本文介绍了需要指导!尝试了解fetch()和Promises的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在尝试使用firebase函数/storeImage和JSON.Stringify()获取已上传(到Firebase)的两个图像的URL和URLPath.

Basically I'm trying to fetch the URL and URLPaths for two images I've uploaded (to Firebase) using the firebase function /storeImage and JSON.Stringify().

下面是一段代码,使我能够获取一张图像的数据.

Below is the snippet of code that enables me to fetch data for the ONE image.

.then(token => {
    authToken = token;
    return fetch("myappURL/storeImage", 
     {
       method: "POST",
       body: JSON.stringify({
       image: image.base64
       }),
       headers: {
         Authorization: "Bearer " + authToken,
       }
      });
    })
    .catch(err => {
        console.log(err);
        alert("Oops! Something went wrong, please try again1")
        dispatch(uiStopLoading());
    })
.then(res => {
        if (res.ok) {
            return res.json();
        } else {
            throw(new Error());
        }
    })
.then(parsedRes => {console.log(parsedRes);

现在我想从第二张图像中获取数据.

Now I want to fetch data from a second image.

从我阅读的文档中收集到的信息是,我应该对多个异步调用使用promise,例如上面的内容.所以,这样的东西(见下文)行不通吗?

What I gather, from the docs I've read, is that I should use promises for multiple async calls like what I have above. So, shouldn't something like this (see below) work?

.then(token => {
    authToken = token;

    let image =  fetch(... image: image.base64 ...);
    let coverImage = fetch(... coverImage: coverImage.base64 ...);

    Promise.all([image, coverImage])
    .then(ress => { ress.forEach(
      res => {
        process( res.json() ); 
   })
})
.catch(err => {...})
.then(res => {...})
.then(parsedRes => {console.log(parsedRes);)

扰流板警报.我尝试了,但没有.但是我不明白为什么.

Spoiler alert. I tried and it didn't. But I cannot understand why.

推荐答案

将诺言链接在一起时,即在 then 回调中启动新的诺言,您需要返回

When you chain promises together, that is, start a new promise inside a then callback you need to return it.

Promise.all 返回一个新的诺言,当传递给它的所有诺言中的 all 解析时,它就会解决.在上面的代码中,您忽略了将其返回.

Promise.all returns a single new promise that resolves when all of the promises passed to it resolve. In your code above you're neglecting to return it.

例如尝试运行这段记录 undefined

E.g. Try running this code which logs undefined

Promise.resolve()
  .then(() => {
    Promise.all([Promise.resolve(1), Promise.resolve(2)])
  })
  .then(result => console.log(result))

此代码记录了 [1、2]

Promise.resolve()
  .then(() => {
    return Promise.all([Promise.resolve(1), Promise.resolve(2)])
  })
  .then(result => console.log(result))

这篇关于需要指导!尝试了解fetch()和Promises的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆