2

배경 해결되지 않는 : 나는 구성 요소와 내 최신 프로젝트 데이터를 반환하는 서버 백엔드를 필요로 반응 생성하기 위해 만드는-반응-응용 프로그램을 사용하고있다수입 비동기 기능이 제대로 데이터

.

'API'파일에서 가져온 기능으로 API에서 반환 한 데이터를 모의하고 싶습니다.

최근에는 비동기/대기 함수를 채택하기 시작했습니다. 주로 읽기 쉽기 때문에.

문제 :에서

내 나는이 API 함수를 가져온 내 구성 요소 중 하나, 나는 원래 내 이해, 기본적으로 약속을 반환하고를 통해 값을 해결할 수 비동기 기능 (로 만든 return 키워드를 사용하고 throw 키워드를 통해 거부하십시오.

그러나 내가 코드를 디버깅 할 때 비동기 함수를 호출 한 다음 즉시 정의되지 않은 "결과"를 계속 콘솔에 표시합니다. .then(res=>{console.log(res)});을 사용하면 즉시 콜백 함수에 들어갑니다. 해결하겠다는 약속을 기다리고있다.

** 이러한 함수를 호출하는 데 사용되는 코드 : **

// I have removed all the other lines of code and left the important code 
import { getVideoList } from './api'; 
runMe = async() => { 
    let res = await getVideolist(); 
    console.log(res); 
} 
<button onClick={this.runMe}>Click Me</button> 

것은이 약속과 기능의 내용을 포장하고, 약속의 해결 기능을 사용할 때, 제대로 작동하는 것입니다.

다음
export let getVideoList = async() => { 
    let random = Math.floor(Math.random() * 3000); 
    setTimeout(() => { 
     let res = [ 
      { 
       video_ID: 3, 
       video_url: 'https:google.com/3', 
       video_description: 'A basic video of exercise', 
       tags: ['upper-body', 'biceps', 'triceps'], 
      }, 
      { 
       video_ID: 2, 
       video_url: 'https:google.com/2', 
       video_description: 'A basic video of exercise', 
       tags: ['upper-body', 'biceps', 'triceps'], 
      }, 
      { 
       video_ID: 1, 
       video_url: 'https:google.com/1', 
       video_description: 'A basic video of exercise', 
       tags: ['upper-body', 'biceps', 'triceps'], 
      }, 
     ]; 
     return res; 
    }, random); 
}; 
export let getTags = async() => { 
    let random = Math.floor(Math.random() * 3000); 
    setTimeout(() => { 
     return [ 
      { tag_ID: 1, tagName: 'upper-body' }, 
      { tag_ID: 2, tagName: 'biceps' }, 
      { tag_ID: 3, tagName: 'triceps' }, 
      { tag_ID: 4, tagName: 'shoulders' }, 
     ]; 
    }, random); 
}; 
export let getVideos = async() => { 
    let random = Math.floor(Math.random() * 3000); 
    setTimeout(() => { 
     let res = [ 
      { video_ID: 3, video_url: 'https:google.com/3', video_description: 'A basic video of exercise' }, 
      { video_ID: 2, video_url: 'https:google.com/2', video_description: 'A basic video of exercise' }, 
      { video_ID: 1, video_url: 'https:google.com/1', video_description: 'A basic video of exercise' }, 
     ]; 
     return res; 
    }, random); 
}; 

작동 수정 된 코드입니다 : 여기

원래 코드

export let getVideoList = async() => { 
    return new Promise((res, rej) => { 
     let random = Math.floor(Math.random() * 3000); 
     setTimeout(() => { 
      res([ 
       { 
        video_ID: 3, 
        video_url: 'https:google.com/3', 
        video_description: 'A basic video of exercise', 
        tags: ['upper-body', 'biceps', 'triceps'], 
       }, 
       { 
        video_ID: 2, 
        video_url: 'https:google.com/2', 
        video_description: 'A basic video of exercise', 
        tags: ['upper-body', 'biceps', 'triceps'], 
       }, 
       { 
        video_ID: 1, 
        video_url: 'https:google.com/1', 
        video_description: 'A basic video of exercise', 
        tags: ['upper-body', 'biceps', 'triceps'], 
       }, 
      ]); 
      return res; 
     }, random); 
    }); 
}; 
export let getTags = async() => { 
    return new Promise((res, rej) => { 
     let random = Math.floor(Math.random() * 3000); 
     setTimeout(() => { 
      res([ 
       { tag_ID: 1, tagName: 'upper-body' }, 
       { tag_ID: 2, tagName: 'biceps' }, 
       { tag_ID: 3, tagName: 'triceps' }, 
       { tag_ID: 4, tagName: 'shoulders' }, 
      ]); 
     }, random); 
    }); 
}; 
export let getVideos = async() => { 
    return new Promise((res, rej) => { 
     let random = Math.floor(Math.random() * 3000); 
     setTimeout(() => { 
      res([ 
       { video_ID: 3, video_url: 'https:google.com/3', video_description: 'A basic video of exercise' }, 
       { video_ID: 2, video_url: 'https:google.com/2', video_description: 'A basic video of exercise' }, 
       { video_ID: 1, video_url: 'https:google.com/1', video_description: 'A basic video of exercise' }, 
      ]); 
     }, random); 
    }); 
}; 

내가 확실하지 오전 같은 왜 이런 일에, 나는 검색 시도 비동기 적으로 가져 오기를 사용하는 새로운 주제에 대해서만 생각해 봤습니다.

이 프로젝트와 관련하여 큰 문제는 아니지만 향후 프로젝트를 위해이 장의 맨 아래에 나와 있습니다. 비동기 작업 할

개정 코드/기다리고 :

const timer = ms => new Promise(res => setTimeout(res, ms)); 
export let getVideoList = async() => { 
    let random = Math.floor(Math.random() * 3000); 
    await timer(random); 
    let res = [ 
     { 
      video_ID: 3, 
      video_url: 'https:google.com/3', 
      video_description: 'A basic video of exercise', 
      tags: ['upper-body', 'biceps', 'triceps'], 
     }, 
     { 
      video_ID: 2, 
      video_url: 'https:google.com/2', 
      video_description: 'A basic video of exercise', 
      tags: ['upper-body', 'biceps', 'triceps'], 
     }, 
     { 
      video_ID: 1, 
      video_url: 'https:google.com/1', 
      video_description: 'A basic video of exercise', 
      tags: ['upper-body', 'biceps', 'triceps'], 
     }, 
    ]; 
    return res; 
}; 
export let getTags = async() => { 
    let random = Math.floor(Math.random() * 3000); 
    await timer(random); 
    return [ 
     { tag_ID: 1, tagName: 'upper-body' }, 
     { tag_ID: 2, tagName: 'biceps' }, 
     { tag_ID: 3, tagName: 'triceps' }, 
     { tag_ID: 4, tagName: 'shoulders' }, 
    ]; 
}; 
export let getVideos = async() => { 
    let random = Math.floor(Math.random() * 3000); 
    await timer(random); 
    let res = [ 
     { video_ID: 3, video_url: 'https:google.com/3', video_description: 'A basic video of exercise' }, 
     { video_ID: 2, video_url: 'https:google.com/2', video_description: 'A basic video of exercise' }, 
     { video_ID: 1, video_url: 'https:google.com/1', video_description: 'A basic video of exercise' }, 
    ]; 
    return res; 
}; 

FIX : 문제가에서는 setTimeout 내부 값을 반환하는 노력에서 비롯

.

+0

당신은 할 수없는'await''setTimeout' (작은 팁을 타임 아웃 내부에서 돌아 오는 것은 아무것도 ...하지 않습니다) ('Promise'를 반환하지 않는다면) Promise를 반환하는 지연 함수를 생성해야합니다 :'const delay = duration => 새로운 Promise (resolve => setTimeout (resolve, duration)); '그 다음에 기다리는 것을 기다린다'() => ..., 랜덤)' –

+0

캐치를 주셔서 감사합니다, 나는 그것을 OP에서 삭제했습니다. 그러나 비동기 함수가 모든 코드를 동 기적으로 실행하고 반환 또는 throw를 가지지 않으면 자동으로 undefined를 반환 할 것인가, 아니면 (이 경우) settimeout을 기다리고 값을 반환 할 것인가? – BaReinhard

+0

질문을 이해하고 있는지 확신 할 수 없지만'await'없이 비동기 함수를 실행하면 반환되는 것을 묻는다면 Promise를 반환 할 것입니다. –

답변

2
await setTimeout(_=>{...},random) 

setTimeout은 작동하지 않습니다. 약속을 반환하지 않습니다.그것을 promisify 수 :

const timer = ms => new Promise(res => setTimeout(res,ms)); 

그래서 당신이

async whatever(){ 
    await timer(1000); 
    return { ... }; 
} 

수행 할 수 있습니다