Daolin
Daolin

Reputation: 634

Save results in Promise after it's done

I use Promise to do a http post. I can see results been output inside then(). How can I access data later? Tried resultPromise.then(), did not produce same result.

let resultPromise = 
fetch(cleanUrl, {
    method: 'POST', // or 'PUT'
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
    })
.then(response => response.json())
.then(data => {
    console.log('Success:', data);
})
.catch((error) => {
    console.error('Error:', error);
});
//what I intent to do
if(data.isSafe == ture) {
   //do something
}
else {
    //do somehing
}

Update 1

Added description of what I want to do with data.

Update 2 Move the code inside then() as @Nicholas Tower suggested.

Upvotes: 1

Views: 62

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85102

.then(data => {
  console.log('Success:', data);
})

Since there's no return value here, the promise it creates resolves to undefined. Either delete this .then (in which case the previous .then will determine the value), or have it re-return the data.

.then(data => {
   console.log('Success:', data);
   return data;
})

The .catch block may require similar treatment. Any errors are currently being swallowed and replaced with resolving to undefined. If you want to re-throw the error, do one of the following:

.catch((error) => {
  console.error('Error:', error);
  throw error;
});

// or
.catch((error) => {
  console.error('Error:', error);
  return Promise.reject(error);
});

Upvotes: 2

Related Questions