Promise.all (). then () 해결?
노드 4.x 사용. 당신이이있을 때 Promise.all(promises).then()
데이터를 해결하고 다음에 전달하는 적절한 방법은 무엇입니까 .then()
?
다음과 같이하고 싶습니다.
Promise.all(promises).then(function(data){
// Do something with the data here
}).then(function(data){
// Do more stuff here
});
하지만 데이터를 2nd로 가져 오는 방법을 잘 모르겠습니다 .then()
. resolve(...)
처음 에는 사용할 수 없습니다 .then()
. 나는 이것을 할 수 있다고 생각했다.
return Promise.all(promises).then(function(data){
// Do something with the data here
return data;
}).then(function(data){
// Do more stuff here
});
하지만 그렇게하는 것이 적절한 방법이 아닌 것 같습니다 ... 이에 대한 올바른 접근 방식은 무엇입니까?
하지만 그게 적절한 방법이 아닌 것 같습니다 ..
그것은 실제로 그것을 수행하는 적절한 방법입니다 (또는 적어도 그것을 수행 하는 적절한 방법). 이는 프라 미스의 핵심 측면이며 파이프 라인이며 파이프 라인의 다양한 핸들러에서 데이터를 마사지 할 수 있습니다.
예:
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
Promise.all(promises)
.then(data => {
console.log("First handler", data);
return data.map(entry => entry * 10);
})
.then(data => {
console.log("Second handler", data);
});
( catch
간결성을 위해 핸들러가 생략되었습니다. 프로덕션 코드에서는 항상 promise를 전파하거나 거부를 처리합니다.)
그 결과는 다음과 같습니다.
첫 번째 핸들러 [1,2] 두 번째 핸들러 [10,20]
... 첫 번째 핸들러는 두 개의 promise ( 1
및 2
) 의 해상도를 배열로 얻은 다음 각각에 10을 곱한 새 배열을 만들고 반환하기 때문입니다. 두 번째 핸들러는 첫 번째 핸들러가 반환 한 것을 가져옵니다.
추가 작업이 동기식이면 첫 번째 처리기 에 넣을 수도 있습니다 .
예:
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
Promise.all(promises)
.then(data => {
console.log("Initial data", data);
data = data.map(entry => entry * 10);
console.log("Updated data", data);
return data;
});
... 비동기 적이라면 결국 중첩되기 때문에 그렇게하고 싶지 않을 것입니다. 중첩은 금방 벗어날 수 있습니다.
오늘날 NodeJS는 새로운 async/await
구문을 지원 합니다. 이것은 쉬운 구문이며 삶을 훨씬 쉽게 만듭니다.
async process() { // must be an async function
var x=Promises.all(promises); // now x will be an array
x=x.map (tmp=>tmp+1); // proccessing the data. No need to .then
}
process().catch(err=>{throw new Error(err)}) // In case of error throw it
더 알아보기:
참고 URL : https://stackoverflow.com/questions/33073509/promise-all-then-resolve
'your programing' 카테고리의 다른 글
혼란스러운 템플릿 오류 (0) | 2020.10.12 |
---|---|
왜`finally`의 리턴이`try`보다 우선합니까? (0) | 2020.10.12 |
Python-virtualenv를 사용하여 수동으로 패키지 설치 (0) | 2020.10.12 |
간단한 DateTime SQL 쿼리 (0) | 2020.10.12 |
'jquery-2.0.2.min.map을 찾을 수 없음'오류 (0) | 2020.10.12 |